import { _decorator, Component, Input, input, EventKeyboard, KeyCode, Animation, RigidBody2D, Node } from 'cc';
const { ccclass, property } = _decorator;

const InputKey = {}

@ccclass('HeroController')
export class HeroController extends Component {

    @property({ type: Component })
    dialogNode: Component;

    private _speed: number = 500;

    private _state: string = '';

    private _directX: number = 0;

    private _directY: number = 0;

    onLoad() {
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
        console.log('键盘事件初始化完成!');
    }

    onDestroy() {
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

    onKeyDown(event: EventKeyboard) {
        InputKey[event.keyCode] = true;
    }

    onKeyUp(event: EventKeyboard) {
        InputKey[event.keyCode] = false;
    }

    setState(state) {
        if (state == this._state) return;
        this._state = state;

        const animationComponent = this.node.getComponent(Animation);
        animationComponent.play(this._state)
    }

    protected start(): void {

    }

    protected update(dt: number): void {
        //如果有对话框, 禁止移动
        if (this.dialogNode && this.dialogNode.node.active) return;

        if (InputKey[KeyCode.KEY_A] || InputKey[KeyCode.ARROW_LEFT]) {
            this._directX = -1

        } else if (InputKey[KeyCode.KEY_D] || InputKey[KeyCode.ARROW_RIGHT]) {
            this._directX = 1
        } else {
            this._directX = 0
        }

        if (InputKey[KeyCode.KEY_W] || InputKey[KeyCode.ARROW_UP]) {
            this._directY = 1

        } else if (InputKey[KeyCode.KEY_S] || InputKey[KeyCode.ARROW_DOWN]) {
            this._directY = -1
        } else {
            this._directY = 0
        }

        let lv = this.node.getComponent(RigidBody2D).linearVelocity;

        if (this._directX) {
            lv.x = this._directX * this._speed * dt;
            lv.y = 0;
        } else if (this._directY) {
            lv.x = 0;
            lv.y = this._directY * this._speed * dt;
        } else {
            lv.x = lv.y = 0;
        }

        this.node.getComponent(RigidBody2D).linearVelocity = lv;

        let state: string = '';
        if (this._directX == 1) {
            state = 'hero_right';
        } else if (this._directX == -1) {
            state = 'hero_left';
        } else if (this._directY == 1) {
            state = 'hero_up';
        } else if (this._directY == -1) {
            state = 'hero_down';
        }

        if (state) this.setState(state);


    }
}


